package com.work.yshop.mvp.model;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.work.yshop.model.Order;
import com.work.yshop.mvp.contract.OrderContract;
import com.work.yshop.provider.UserDataProvider;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单数据模型类 - MVP架构
 */
public class OrderModel implements OrderContract.Model {

    private static final String TAG = "OrderModel";
    private Context context;
    private ContentResolver contentResolver;

    public OrderModel(Context context) {
        this.context = context;
        this.contentResolver = context.getContentResolver();
    }

    @Override
    public List<Order> getOrderList(int status) {
        List<Order> orders = new ArrayList<>();

        try {
            // 构建查询条件
            String selection = null;
            String[] selectionArgs = null;

            if (status > 0) {
                selection = "status = ?";
                selectionArgs = new String[]{String.valueOf(status)};
            }

            // 查询数据库获取订单列表
            Cursor cursor = contentResolver.query(
                    UserDataProvider.ORDERS_URI,
                    null,
                    selection,
                    selectionArgs,
                    "order_time DESC"
            );

            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        Order order = extractOrderFromCursor(cursor);
                        if (order != null) {
                            orders.add(order);
                        }
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取订单列表失败", e);
        }

        // 如果数据库中没有数据，添加模拟数据
        if (orders.isEmpty() && status >= 0) {
            orders = createMockOrders(status);
        }

        return orders;
    }

    @Override
    public boolean addOrder(Order order) {
        try {
            // 创建ContentValues对象
            ContentValues values = new ContentValues();
            values.put("order_number", order.getOrderNumber());
            values.put("buyer_name", order.getBuyerName());
            values.put("order_time", order.getOrderTime());
            values.put("total_amount", order.getTotalAmount());
            values.put("status", order.getStatus());
            values.put("user_id", UserSession.getInstance().getUserId());

            // 插入数据到ContentProvider
            Uri uri = contentResolver.insert(UserDataProvider.ORDERS_URI, values);

            return uri != null;
        } catch (Exception e) {
            Log.e(TAG, "添加订单失败", e);
            return false;
        }
    }

    @Override
    public boolean updateOrderStatus(Order order, int status) {
        try {
            // 创建ContentValues对象
            ContentValues values = new ContentValues();
            values.put("status", status);

            // 更新数据
            int rowsAffected = contentResolver.update(
                    UserDataProvider.ORDERS_URI,
                    values,
                    "order_number = ?",
                    new String[]{order.getOrderNumber()}
            );

            return rowsAffected > 0;
        } catch (Exception e) {
            Log.e(TAG, "更新订单状态失败", e);
            return false;
        }
    }

    @Override
    public boolean deleteOrder(Order order) {
        try {
            // 删除数据
            int rowsAffected = contentResolver.delete(
                    UserDataProvider.ORDERS_URI,
                    "order_number = ?",
                    new String[]{order.getOrderNumber()}
            );

            return rowsAffected > 0;
        } catch (Exception e) {
            Log.e(TAG, "删除订单失败", e);
            return false;
        }
    }

    /**
     * 从Cursor中提取订单数据
     */
    private Order extractOrderFromCursor(Cursor cursor) {
        try {
            String orderNumber = cursor.getString(cursor.getColumnIndexOrThrow("order_number"));
            String buyerName = cursor.getString(cursor.getColumnIndexOrThrow("buyer_name"));
            String orderTime = cursor.getString(cursor.getColumnIndexOrThrow("order_time"));
            double totalAmount = cursor.getDouble(cursor.getColumnIndexOrThrow("total_amount"));
            int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));

            return new Order(orderNumber, buyerName, orderTime, totalAmount, status);
        } catch (Exception e) {
            Log.e(TAG, "提取订单数据失败", e);
            return null;
        }
    }

    /**
     * 创建模拟订单数据
     */
    private List<Order> createMockOrders(int status) {
        List<Order> orders = new ArrayList<>();

        // 添加模拟数据
        if (status == 0 || status == Order.STATUS_PENDING) {
            orders.add(new Order("O2023051001", "张三", "2023-05-10 14:30", 59.8, Order.STATUS_PENDING));
            orders.add(new Order("O2023051002", "李四", "2023-05-10 15:45", 128.5, Order.STATUS_PENDING));
        }

        if (status == 0 || status == Order.STATUS_PROCESSING) {
            orders.add(new Order("O2023050901", "王五", "2023-05-09 09:20", 45.0, Order.STATUS_PROCESSING));
        }

        if (status == 0 || status == Order.STATUS_SHIPPED) {
            orders.add(new Order("O2023050801", "赵六", "2023-05-08 16:10", 76.5, Order.STATUS_SHIPPED));
            orders.add(new Order("O2023050802", "钱七", "2023-05-08 18:30", 32.0, Order.STATUS_SHIPPED));
        }

        if (status == 0 || status == Order.STATUS_COMPLETED) {
            orders.add(new Order("O2023050701", "孙八", "2023-05-07 10:15", 98.0, Order.STATUS_COMPLETED));
            orders.add(new Order("O2023050601", "周九", "2023-05-06 14:50", 120.5, Order.STATUS_COMPLETED));
        }

        if (status == 0 || status == Order.STATUS_CANCELED) {
            orders.add(new Order("O2023050501", "吴十", "2023-05-05 11:25", 65.0, Order.STATUS_CANCELED));
        }

        return orders;
    }
} 